<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 800px;
}

.input-item {
  height: 2.2rem;
}

.input-card-ControlBar {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: .25rem;
  width: 10rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  position: fixed;
  bottom: 12rem;
  right: 2rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}

.my-panel {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: .25rem;
  width: 10rem;
  height: 10rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  position: fixed;
  bottom: 35rem;
  right: 22rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}

.input-card-MouseTool {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: .25rem;
  width: 10rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  position: fixed;
  bottom: 12rem;
  right: 12rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}
</style>
<template>
  <div>
    <div id="container"> </div>
    <div class="my-panel" id="my-panel">


    </div>
    <div class='input-card-ControlBar' v-show="visible">
      <div class="input-item">
        <checkbox @change="toggleScale" :checked="toggleScaleCheck">比例尺</checkbox>
      </div>

      <div class="input-item">
        <checkbox @change="toggleToolBar" :checked="toggleToolBarCheck">工具条</checkbox>
      </div>

      <div class="input-item">
        <checkbox @change="toggleControlBar" :checked="toggleControlBarCheck">工具条方向盘</checkbox>
      </div>

      <div class="input-item">
        <checkbox @change="toggleOverViewShow" :checked="toggleOverViewShowCheck">显示鹰眼</checkbox>
      </div>
    </div>
    <div class="input-card-MouseTool" style='width: 24rem;' v-show="visible">
      <div class="input-item">
        左击获取经纬度: <input type="text" :value="clickValue" v-show="visible">
      </div>
    </div>
    <div class="add-btn-block">
      <div class="button" @click="cancelEvent">取消</div>
      <div class="button" @click="initPathAssign">提交</div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: 'ff652b8278a970e68e67a0cd5e63d8d4',
}
export default {
  name: 'MapDragRoute',
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    visible: Boolean,
    drewData: Array,
    routePathP: Array,
    districtP: String,
  },
  data() {
    //这里存放数据
    return {
      AMap: null,
      //此处不声明 map 对象，可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
      mapd: null,
      mouseTool: null,
      //监听draw事件可获取画好的覆盖物
      overlays: [],
      auto: null,
      placeSearch: null,
      drawOptionValue: '',
      drawOptions: [
        { label: '画点', value: 'marker' },
        { label: '画折线', value: 'polyline' },
        { label: '画多边形', value: 'polygon' },
        { label: '画矩形', value: 'rectangle' },
        { label: '画圆', value: 'circle' },
        { label: '路径规划', value: 'routePath' },
        { label: '获取经纬度', value: 'position' },
      ],
      //--地图控件 --
      toggleOverViewShowCheck: true,
      toggleControlBarCheck: true,
      toggleToolBarCheck: true,
      toggleScaleCheck: true,
      scale: null,
      toolBar: null,
      controlBar: null,
      overView: null,
      //坐击经纬度
      clickValue: '',
      //可拖拽路线规划
      route: null,
      routePath: [],
      startAndEnd: [],
      district: '',
      lnglat: '',
      path: [[102.886972, 24.955915], [103.166995, 24.788511]]
    };
  },
  //计算属性 类似于 data 概念
  computed: {


  },
  //监控 data 中的数据变化
  watch: {
    overlays(newVal, oldVal) {
      this.$emit('getOverlaysValue', newVal)
    },
    drewData(newValue, oldValue) {
      this.mountDrewData()
    },
    districtP(newValue, oldValue) {
      this.district = this.districtP;
      this.initPlaceSearch(this.AMap)
    },

    // routePathP(newValue, oldValue) {
    //   let _this = this;
    //   console.log('这个值变化了么')
    //   _this.routePath=_this.routePathP
    //   if(this.routePathP.length>1){
    //     console.log(this.routePathP)
    //     this.initPathAssign(this.routePathP)
    //   }

    // },

    routePathP(newValue, oldValue) {

      let _this = this;
      console.log('routePathP 发生变化' + _this.routePathP);
    
      this.initMap()
      this.initPathAssign()
      // 将 routePathP 的新值赋给 startAndEnd
      // if (this.startAndEnd.length === 2) {
      //   this.routePath = this.startAndEnd.map(item => {
      //     return item.getPosition();
      //   });
      //   console.log(this.routePath);
      //   this.initPathAssign(this.routePath); // 传递 routePath 给 initPathAssign 方法
      //   this.startAndEnd.forEach(item => {
      //     item.remove();
      //   });
      //   this.startAndEnd = [];
      // }
    },

    // startAndEnd(newValue, oldValue) {
    //   console.log('进来有撒用11')
    //   let _this = this;

    //   this.startAndEnd = _this.routePathP
    //   if (this.startAndEnd.length == 2) {
    //     this.routePath = this.startAndEnd.map(item => {
    //       return item.getPosition()
    //     })
    //     console.log(this.routePath)
    //     this.initPathAssign()
    //     this.startAndEnd.forEach(item => {
    //       item.remove()
    //     })
    //     this.startAndEnd = []
    //   }
    // }
  },
  //方法集合
  methods: {
    toggleOverViewShow(e) {
      this.toggleOverViewShowCheck = e.target.checked
      if (e.target.checked) {
        this.overView.show();
      } else {
        this.overView.hide();
      }
    },
    toggleControlBar(e) {
      this.toggleControlBarCheck = e.target.checked
      if (e.target.checked) {
        this.controlBar.show()
      } else {
        this.controlBar.hide()
      }
    },
    toggleToolBar(e) {
      this.toggleToolBarCheck = e.target.checked
      if (e.target.checked) {
        this.toolBar.show();
      } else {
        this.toolBar.hide();
      }
    },
    toggleScale(e) {
      this.toggleScaleCheck = e.target.checked
      if (e.target.checked) {
        this.scale.show();
      } else {
        this.scale.hide();
      }
    },
    closeDram() {
      this.mouseTool.close(true)
      this.drawOptionValue = ''
    },
    clearMap() {
      this.mapd.remove(this.overlays)
      this.overlays = [];
      this.route.destroy()
      this.$emit('getRoutePath', [])
      // this.$emit('getOverlaysValue', this.overlays)
    },
    onChangeDrawOption(e) {
      console.log('radio checked', e.target.value);
      this.draw(e.target.value)
    },
    initMapTool() {
      this.scale = new AMap.Scale();
      this.toolBar = new AMap.ToolBar({
        position: {
          top: '110px',
          right: '40px'
        }
      });
      this.controlBar = new AMap.ControlBar({
        position: {
          top: '10px',
          right: '10px',
        }
      });
      this.overView = new AMap.HawkEye({
        position: {
          top: '10px',
          left: '10px',
        },
        opened: false
      });
      this.mapd.addControl(this.scale);
      this.mapd.addControl(this.toolBar);
      this.mapd.addControl(this.controlBar);
      this.mapd.addControl(this.overView);
    },
    initMouseTool(AMap) {
      console.log('这个方法有撒用222')
      this.mouseTool = new AMap.MouseTool(this.mapd);
      // 监听draw事件可获取画好的覆盖物
      this.mouseTool.on('draw', function (e) {
        this.overlays.push(e.obj);
      }.bind(this))
      //为地图注册click事件获取鼠标点击出的经纬度坐标
      this.mapd.on('click', function (e) {
        if (this.drawOptionValue == 'routePath') {
          if (this.startAndEnd.length == 0) {
            let start = new AMap.Marker({
              icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
              position: [e.lnglat.getLng(), e.lnglat.getLat()],
              offset: new AMap.Pixel(-13, -30)
            });
            start.setMap(this.mapd);
            this.startAndEnd.push(start)
          } else if (this.startAndEnd.length == 1) {
            let end = new AMap.Marker({
              icon: "https//webapi.amap.com/theme/v1.3/markers/n/end.png",
              position: [e.lnglat.getLng(), e.lnglat.getLat()],
              offset: new AMap.Pixel(-13, -30)
            });
            end.setMap(this.mapd);
            this.startAndEnd.push(end)
          }
        }
        if (this.drawOptionValue == 'position') {
          this.clickValue = e.lnglat.getLng() + ',' + e.lnglat.getLat()
        }

      }.bind(this));
      this.mountDrewData()

    },
    mountDrewData() {
      if (this.drewData != null) {
        this.drewData.forEach(item => {
          this.drew(item.overlayType, item.opts)
        })
      }
    },

    updateMindPointContext: function () {
      let pathList = this.route._list
      console.log(pathList)
      let startPoint = pathList[0]
      let endPoint = pathList[pathList.length - 1]
      let mindPoint = []
      pathList.forEach(item => {
        if (item.id != startPoint.id && item.id != endPoint.id) {
          mindPoint.push(item)
        }
      })
      let count = 1
      mindPoint.forEach(item => {
        item.marker._opts.label.content = '经过点' + count
        count++
        item.marker.setContent('')//需要set一下上面代码才会生效
      })
      pathList = []
      pathList.push(startPoint)
      pathList.push(...mindPoint)
      pathList.push(endPoint)
      this.route._list = pathList
    },



    initPathAssign() {
      console.log(typeof this.routePathP);

      console.log("我得坐标传进来" + JSON.stringify(this.routePathP));

      console.log("我得坐标传进来" + this.routePathP);
      // 将路径数据转换为坐标对象数组
      const coordinates = this.routePathP.map(coord => {
        const [lng, lat] = coord[0].split(',');
        return new AMap.LngLat(parseFloat(lng), parseFloat(lat));
      });
      this.route = new AMap.DragRoute(this.mapd, coordinates, AMap.DrivingPolicy.LEAST_FEE); //构造拖拽导航类

      this.route.search(); //查询导航路径并开启拖拽导航
      console.log('执1' + this.route.getWays())

      this.route.on('addway', function (e) {
        // e.target.midMarkerOptions.icon= '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-'+(this.route.getWays().length+1)+'.png'
        // e.target.midMarkerOptions.label.content = '路径点' + (this.route.getWays().length + 1)
        console.log('拿到途径数据坐标了么' + this.route._path)
        this.$emit('getRoutePath', this.route._path)
      }.bind(this))
      //this.updateMindPointContext();
    },

    initMap() {
      AMapLoader.load({
        key: "de0ccfacaee224fb23e8954ea4cfb971",             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": [
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.ToolBar",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.ControlBar",
          "AMap.MouseTool",
          "AMap.DragRoute"],         // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.AMap = AMap
        this.mapd = new AMap.Map("container", {  //设置地图容器id
          viewMode: "2D",  //  是否为3D地图模式
          zoom: 13,   // 初始化地图级别
          center: [102.892851, 24.897518], //中心点坐标  昆明
          resizeEnable: true
        });

        // 添加点击事件监听器
        this.mapd.on('rightclick', (event) => {
          // 获取点击位置的经纬度
          this.lnglat = event.lnglat;
          this.$emit('handleCoordinates', this.lnglat);

        });
        if (this.routePath !== null) {
          console.log('初始化' + this.routePath)
          //路径规划工具初始化
          this.initPathAssign();
        }
        //this.initMouseTool();
        //地图工具
        this.initMapTool();



        this.initPlaceSearch();


      }).catch(e => {
        console.log(e);
      })
    },
    initPlaceSearch(AMap) {


      this.placeSearch = new AMap.PlaceSearch({
        pageSize: 5, //单页显示结果条数
        pageIndex: 1, //页码
        // city: "010", //兴趣点城市
        // citylimit: true, //是否强制限制在设置的城市内搜索
        map: this.mapd, //展现结果的地图实例
        panel: "my-panel", //结果列表将在此容器中进行展示。
        autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
      });
      console.log(this.districtP)
      this.placeSearch.search(this.districtP);

    },


    draw(type) {
      switch (type) {
        case 'marker': {
          this.mouseTool.marker({
            //同Marker的Option设置
          });
          break;
        }
        case 'polyline': {
          this.mouseTool.polyline({
            strokeColor: '#80d8ff'
            //同Polyline的Option设置
          });
          break;
        }
        case 'polygon': {
          this.mouseTool.polygon({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
          });
          break;
        }
        case 'rectangle': {
          this.mouseTool.rectangle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
          });
          break;
        }
        case 'circle': {
          this.mouseTool.circle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Circle的Option设置
          });
          break;
        }
      }
    },
    drew(type, opts) {
      switch (type) {
        case 'marker': {
          opts.map = this.mapd
          let o = new AMap.Marker(opts);
          this.overlays.push(o);
          break;
        }
        case 'polyline': {
          opts.map = this.mapd
          let o = new AMap.Polyline(opts)
          this.overlays.push(o);
          break;
        }
        case 'polygon': {
          opts.map = this.mapd
          let o = new AMap.Polygon(opts)
          this.overlays.push(o);
          break;
        }
        case 'rectangle': {
          opts.map = this.mapd
          let o = new AMap.Rectangle(opts)
          this.overlays.push(o);
          break;
        }
        case 'circle': {
          opts.map = this.mapd
          let o = new AMap.Circle(opts)
          this.overlays.push(o);
          break;
        }
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.initMap();
  },
  //生命周期 - 创建之前
  beforeCreate() {
  },
  //生命周期 - 挂载之前
  beforeMount() {
  },
  //生命周期 - 更新之前
  beforeUpdate() {
  },
  //生命周期 - 更新之后
  updated() {
  },
  //生命周期 - 销毁之前
  beforeDestroy() {
  },
  //生命周期 - 销毁完成
  destroyed() {
  },
  //如果页面有 keep-alive 缓存功能， 这个函数会触发
  activated() {
  },
}
</script>


